package com.sina.shop.manage.controller.admin;

import com.sina.shop.core.exception.server.UpdateException;
import com.sina.shop.domain.admin.Permission;
import com.sina.shop.domain.admin.Role;
import com.sina.shop.manage.service.admin.PermissionManageService;
import com.sina.shop.manage.service.admin.RoleManageService;
import com.sina.shop.util.StringUtils;
import com.sina.shop.web.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * 段浩杰   2017-12-20-16:44
 */
@Controller
@RequestMapping("roleManage")
public class RoleManageController extends BaseController {

    @Autowired
    @Qualifier("roleManageService")
    private RoleManageService roleManageService;

    @Autowired
    @Qualifier("permissionManageService")
    private PermissionManageService permissionManageService;

    //@RequiresRoles("admin")
    @RequestMapping(value = "getRoleList", method = RequestMethod.GET)
    public ModelAndView getRoleList(@Valid Role role) {
        LOG.info("role:{}", role);

        Map<String, Object> result = new HashMap<>(6);
        ModelAndView mv = new ModelAndView("resultView");
        Long count[] = new Long[1];
        List<Map<String, Object>> roleList = roleManageService.getRoleList(role, count);
        Map<String, Object> data = new HashMap<>(4);

        data.put("recordsTotal", count[0]);
        data.put("recordsFiltered", count[0]);
        data.put("data", roleList);

        result.put(CODE, OK);
        result.put(DATA, data);
        mv.addObject(RESULT, result);

        return mv;
    }

    @RequestMapping(value = "getRoleIdAndNameList", method = RequestMethod.GET)
    public ModelAndView getRoleIdAndNameList() {

        ModelAndView mv = new ModelAndView("resultView");
        Map<String, Object> result = new HashMap<>(6);

        List<Map<String, Object>> roleList = roleManageService.getRoleIdAndNameList();

        Map<String, Object> data = new HashMap<>(4);
        data.put("data", roleList);

        result.put(CODE, OK);
        result.put(DATA, data);
        mv.addObject(RESULT, result);

        return mv;
    }

    //@RequiresRoles("admin")
    @RequestMapping(value = "getRole", method = RequestMethod.GET)
    public ModelAndView getRole(String name) {
        LOG.info("name:{}", name);

        ModelAndView mv = new ModelAndView("resultView");
        Role role = roleManageService.getRoleByName(name);
        mv.addObject(RESULT, role);

        return mv;
    }

    @RequestMapping(value = "getRoleById", method = RequestMethod.GET)
    public ModelAndView getRoleById(Long id) {
        LOG.info("id:{}", id);

        ModelAndView mv = new ModelAndView("resultView");
        Role role = roleManageService.getRoleById(id);
        mv.addObject(RESULT, role);

        return mv;
    }


    //支持批量删除，各个id之间用“，”隔开
    //@RequiresRoles("admin")
    @RequestMapping(value = "deleteRole", method = RequestMethod.POST)
    public ModelAndView deleteRole(Long id) {
        LOG.info("id:{}", id);

        ModelAndView mv = new ModelAndView("resultView");
        Map<String, Object> result = new HashMap<>(4);

        try {
            roleManageService.deleteRole(id);
            result.put(CODE, OK);
            result.put(MSG, "删除角色成功");
        } catch (UpdateException e) {
            result.put(CODE, e.getResultCode());
            result.put(MSG, e.getMessage());
        }
        mv.addObject(RESULT, result);
        return mv;
    }

    //@RequiresRoles("admin")
    @RequestMapping(value = "updateRole", method = RequestMethod.POST)
    public ModelAndView updateRole(@Valid Role role, String pid) {
        LOG.info("role:{}，pid:{}", role, pid);

        ModelAndView mv = new ModelAndView("resultView");
        Map<String, Object> result = new HashMap<>(4);
        role.setPermissions(getPById(pid));
        try {
            roleManageService.updateRole(role);
            result.put(CODE, OK);
            result.put(MSG, "更新角色成功");
        } catch (UpdateException e) {
            result.put(CODE, e.getResultCode());
            result.put(MSG, e.getMessage());
        }

        mv.addObject(RESULT, result);

        return mv;
    }

    //@RequiresRoles("admin")
    @RequestMapping(value = "saveRole", method = RequestMethod.POST)
    public ModelAndView saveRole(@Valid Role role, String pids) {
        LOG.info("role:{},pids:{}", role, pids);

        ModelAndView mv = new ModelAndView("resultView");
        Map<String, Object> result = new HashMap<>(4);
        role.setPermissions(getPermissionById(pids));
        try {
            roleManageService.saveRole(role);
            result.put(CODE, OK);
            result.put(MSG, "新增角色成功");
        } catch (UpdateException e) {
            result.put(CODE, e.getResultCode());
            result.put(MSG, e.getMessage());
        }

        mv.addObject(RESULT, result);

        return mv;
    }

    @RequestMapping(value = "getRoleListToHtml", method = RequestMethod.GET)
    public ModelAndView getRoleListToHtml() {

        ModelAndView mv = new ModelAndView("admin/roleList");
        return mv;
    }

    private Set<Permission> getPermissionById(String pid) {

        Set<Permission> permissions = new HashSet<>();

        if (!StringUtils.isEmpty(pid)) {
            //分割
            String pids[] = pid.split(",");
            for (String p : pids) {
                if (!StringUtils.isEmpty(p)) {
                    //得到对应的permission
                    Permission permission = permissionManageService.getPermissionById(Long.valueOf(p));
                    //放入集合
                    if (permission != null) {
                        permissions.add(permission);
                    }
                }
            }
        } else {
            //如果字符串为空返回null
            permissions = null;
        }
        //判断是否为空或者size为0
        if (permissions == null || permissions.size() == 0) {
            return null;
        }

        return permissions;
    }

    private Set<Permission> getPById(String pid) {

        Set<Permission> permissions = new HashSet<>();

        if (!StringUtils.isEmpty(pid)) {
            //分割
            String pids[] = pid.split(",");
            for (String p : pids) {
                if (!StringUtils.isEmpty(p)) {
                    //得到对应的permission
                    Permission permission = new Permission();
                    permission.setId(Long.valueOf(p));
                    //放入集合
                    permissions.add(permission);
                }
            }
        } else {
            //如果字符串为空返回null
            permissions = null;
        }
        //判断是否为空或者size为0
        if (permissions == null || permissions.size() == 0) {
            return null;
        }
        return permissions;
    }
}
